package nettysocket;/**
 * Created by zhanghb on 2019/9/2.
 */

/**
 * @Description
 * @Author Zhanghb
 * @Date
 */

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Server {
    private final int port = 8001;

    public Server() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup, workerGroup).option(ChannelOption.SO_KEEPALIVE, true).channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel sc) throws Exception {
                        // 发送字符串的编码器。
                        sc.pipeline().addLast(new StringEncoder());
                        // 接收到字符串的解码器。
                        sc.pipeline().addLast(new StringDecoder());
                        sc.pipeline().addLast(new MyServerHandler());
                    }
                });

        // 绑定端口，开始接收进来的连接。
        ChannelFuture cf = b.bind(port).sync();

        // 等待服务器关闭Socket。
        cf.channel().closeFuture().sync();
    }

    /**
     * 给springboot启动时调用
     */
    public static void run(){
        try {
            log.info("启动Netty Server");
            new Server();
        } catch (Exception e) {
            log.info("启动Netty Server失败"+e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            new Server();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

